package com.lib.online.controller.rest;

import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.http.HttpStatus; 


import org.springframework.web.bind.annotation.ResponseStatus;

import com.lib.online.model.User;
import com.lib.online.service.BookService;
import com.lib.online.service.UserService;


@Controller
@RequestMapping(value ="/rest_user")
public class RestUserController {
	 @Autowired
	    private BookService bookService;
	 @Autowired
	    private UserService userService;
	 
	 @RequestMapping(value = "{username}+{pass}", method = RequestMethod.GET,
			    headers = {"Accept=text/xml, application/json"})
			    public @ResponseBody
			    User getUser(@PathVariable String username, @PathVariable String pass) {
			    return this.userService.getUser(username, pass);
			    }
	 
	 @RequestMapping(value="{username}+{pass}", method=RequestMethod.DELETE)
	 @ResponseStatus(HttpStatus.NO_CONTENT)
	 public void deleteUser(@PathVariable("username") String username, @PathVariable String pass) {
		 User user = userService.getUser(username, pass);
		  if (user!=null)
			  userService.removeUser(user);
	 }
	 
	 @RequestMapping(value = "create", method = RequestMethod.PUT, 
			 headers = {"Content-Type=application/json , application/json"})			
	 @ResponseStatus(HttpStatus.CREATED)
	 public @ResponseBody User createUser(@RequestBody @Valid User user,
	 BindingResult result, HttpServletResponse response)
	 throws BindException {
	 if(result.hasErrors()) {
	 throw new BindException(result);
	 }
	 userService.addUser(user);
	 
	 response.setHeader("Location", "/rest_user/" + user.getUserFName());
	 return user; 
	 }
	
}
